<template>
  <a-modal v-model:open="open" title="手动管理" :maskClosable="false" :width="600" centered>
    <a-form class="manual-form">
      <a-form-item name="behavior" label="管理行为" style="position: relative">
        <a-select
          v-model:value="state.behaviorType"
          @change="behaviorTypeChange"
          style="width: 100px"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        >
          <a-select-option value="1">健康教育</a-select-option>
          <a-select-option value="2">健康提醒</a-select-option>
          <a-select-option value="3">AI随访</a-select-option>
          <a-select-option value="4">人工随访</a-select-option>
        </a-select>
        <!--      
        <a-auto-complete
          v-if="state.behaviorType == '1' || state.behaviorType == '2'"
          v-model:value="state.runData.templateName"
          :options="state.templateData"
          style="width: 300px; margin-left: 10px"
          :placeholder="placeholderName"
          @select="nameSelect"
        >
        </a-auto-complete> -->
        <a-tooltip placement="top">
          <template v-if="state.runData.templateName" #title>{{
            state.runData.templateName
          }}</template>
          <a-select
            optionFilterProp="label"
            v-model:value="state.runData.templateName"
            show-search
            :placeholder="placeholderName"
            @change="templateTypeChange"
            :style="{
              width: state.behaviorType == '1' || state.behaviorType == '2' ? '300px' : '350px',
              marginLeft: '10px'
            }"
            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          >
            <a-select-option
              v-for="(item, index) in state.templateData"
              :key="index"
              :value="item.templateName"
              :label="item.templateName"
              :option="item"
              >{{ item.templateName }}</a-select-option
            >
          </a-select>
        </a-tooltip>
        <a-button
          @click="addContent"
          style="position: absolute; right: -15px; z-index: 9999"
          type="link"
          v-if="state.behaviorType == '1' || state.behaviorType == '2'"
        >
          新增内容
        </a-button>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="open = false">取消</a-button>
      <a-button type="primary" @click="handleOk" :loading="btnLoading">确定</a-button>
    </template>
  </a-modal>

  <a-modal v-model:open="isAddContent" :title="contentTitle" :width="800" :maskClosable="false">
    <a-form ref="formRef" :model="formState" :rules="formRules">
      <a-form-item
        :label="state.behaviorType == '2' ? '健康提醒名称' : '健康教育名称'"
        name="formName"
      >
        <a-input
          v-model:value="formState.formName"
          :placeholder="state.behaviorType == '2' ? '请输入健康提醒名称' : '请输入健康教育处方名称'"
        ></a-input>
      </a-form-item>
      <a-form-item label="健康提醒类型" name="remindType" v-if="state.behaviorType == '2'">
        <a-select v-model:value="formState.remindType">
          <a-select-option value="1">用药提醒</a-select-option>
          <a-select-option value="2">复查提醒</a-select-option>
          <a-select-option value="3">其他提醒</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        :label="state.behaviorType == '2' ? '健康提醒内容' : '健康教育内容'"
        name="context"
      >
        <a-textarea
          v-model:value="formState.context"
          :placeholder="state.behaviorType == '2' ? '请输入健康提醒内容' : '请输入健康教育内容'"
          show-count
          :maxlength="state.behaviorType == '2' ? 300 : 5000"
          :auto-size="{ minRows: state.behaviorType == '2' ? 4 : 8 }"
        ></a-textarea>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button key="back" @click="isAddContent = false">取消</a-button>
      <a-button @click="saveTemplate" :loading="templateLoading">存为模板</a-button>
      <a-button type="primary" @click="saveContent" :loading="contentLoading">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getTemplateList, manualManage, saveTemplateForm } from '@/api/patientManagement/index.ts'
import { message } from 'ant-design-vue'
import store from '@/store'
const emit = defineEmits(['close'])
const state = reactive({
  behaviorType: '1',
  templateData: [],
  runData: {},
  templateId: ''
})
const open = ref(false)
const placeholderName = ref('请选择教育内容')
const btnLoading = ref(false)

const isAddContent = ref(false)
const groupId = ref()
const patRunId = ref()
const patRunName = ref()
const patDeptCode = ref()

const contentTitle = ref('')
const contentLoading = ref(false)
const templateLoading = ref(false)
const formRef = ref()
const formState: any = reactive({
  formName: '',
  remindType: '2',
  context: ''
})

const checkFormName = (rule, value, callback) => {
  if (!value) {
    return Promise.reject(
      state.behaviorType == '2' ? '请输入健康提醒名称' : '请输入健康教育处方名称'
    )
  }
  return Promise.resolve()
}

const formRules = ref({
  formName: [
    {
      required: true,
      validator: checkFormName,
      trigger: 'blur'
    }
  ],
  remindType: [{ required: true, message: '请选择健康提醒类型', trigger: 'change' }],
  context: [{ required: true, message: '请选择输入健康提醒内容', trigger: 'blur' }]
})

const init = (patId, groupList, id, patName, deptCode) => {
  patRunName.value = patName
  btnLoading.value = false
  patRunId.value = patId
  state.runData = {}
  open.value = true
  state.behaviorType = '1'
  state.templateData = []
  groupId.value = id
  patDeptCode.value = deptCode

  getDataList()
}

const getDataList = async () => {
  let type = ''
  if (state.behaviorType == '3') {
    type = '4'
  } else {
    type = state.behaviorType
  }
  await getTemplateList({
    page: 1,
    limit: 9999,
    templateType: type
  }).then((res) => {
    state.templateData = res.data.list
    state.templateData.forEach((element) => {
      element.value = element.templateName
    })
  })
}

const behaviorTypeChange = (value: any) => {
  state.runData = {}
  state.behaviorType = value
  switch (value) {
    case '1':
      placeholderName.value = '请选择教育内容'
      break
    case '2':
      placeholderName.value = '请选择提醒内容'
      break
    default:
      placeholderName.value = '请选择随访表单'
      break
  }

  getDataList()
}

// 选择下拉数据
const nameSelect = (value, option) => {
  state.runData.templateName = option.templateName
  state.runData.templateType = option.templateType
  state.runData.remindType = option.remindType
  state.runData.patId = patRunId.value
  state.runData.behaviorType = state.behaviorType
  state.runData.context = option.context
  state.templateId = option.id
}

const templateTypeChange = (value, option) => {
  if (state.templateData && state.templateData.length > 0) {
    for (let i = 0; i < state.templateData.length; i++) {
      if (value == state.templateData[i].templateName) {
        state.templateId = state.templateData[i].id
        state.runData.templateId = state.templateId
      }
    }
  }
  state.runData = {
    patId: patRunId.value,
    behaviorType: state.behaviorType,
    templateType: option.option.templateType,
    templateName: option.option.templateName,
    context: option.option.context,
    remindType: option.option.remindType
  }
}

const handleOk = () => {
  if (!Object.keys(state.runData).length) {
    message.warn('请选择相应的内容或模板')
    return
  }
  state.runData.patId = patRunId.value
  state.runData.behaviorType = state.behaviorType
  state.runData.groupId = groupId.value
  state.runData.patName = patRunName.value
  state.runData.userId = store.userApp.userInfo.id
  state.runData.deptCode = patDeptCode.value
  state.runData.templateId = state.templateId
  // state.runData.remindType = formState.remindType

  // state.runData.templateType = formState.remindType
  // state.runData.context = formState.context

  btnLoading.value = true
  manualManage(state.runData)
    .then(() => {
      btnLoading.value = false
      open.value = false
      message.success('手动管理成功')
    })
    .catch(() => {
      btnLoading.value = false
    })
}

const addContent = () => {
  isAddContent.value = true

  templateLoading.value = false
  contentLoading.value = false

  switch (state.behaviorType) {
    case '1':
      contentTitle.value = '新建健康教育处方'
      break
    case '2':
      contentTitle.value = '新建健康提醒'
      break
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const saveContent = () => {
  contentLoading.value = true
  formRef.value
    .validate()
    .then(() => {
      contentLoading.value = false
      isAddContent.value = false
      state.runData.context = JSON.stringify({
        content: formState.context
      })
      state.runData.templateName = formState.formName
      if (formState.remindType) {
        state.runData.remindType = formState.remindType
      }

      state.runData.templateType = state.behaviorType
    })
    .catch((error) => {
      contentLoading.value = false
    })
}

const saveTemplate = () => {
  templateLoading.value = true
  formRef.value
    .validate()
    .then(() => {
      const data = {
        templateType: state.behaviorType,
        templateName: formState.formName,
        context: JSON.stringify({
          content: formState.context
        }),
        remindType: formState.remindType ? formState.remindType : ''
      }
      saveTemplateForm(data)
        .then(async () => {
          message.success('模板保存成功')
          isAddContent.value = false
          templateLoading.value = false
          state.runData.context = JSON.stringify({
            content: formState.context
          })

          state.runData.templateType = state.behaviorType

          await getDataList()
          if (formState.remindType) {
            state.runData.remindType = formState.remindType
          }
          state.runData.templateName = state.templateData[0].templateName
        })
        .catch(() => {
          templateLoading.value = false
        })
    })
    .catch(() => {
      templateLoading.value = false
    })
}

defineExpose({
  init
})
</script>
<style lang="less" scoped>
.manual-form .ant-form-item {
  margin-bottom: 0;
}
</style>
